﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace Agents.Admin
{
    //this page allows the administrater to edit a product.
    public partial class EditProduct : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            //only spill information if we just entered the page.
            if (Page.IsPostBack == false)
            {
                int productId = Int32.Parse(Request.QueryString["productId"]);
                Queries q = new Queries();
                Product product = q.GetProduct(productId);

                nameTxtbox.Text = product.Name;

                //spilling the current price of product to screen.
                priceTxtbox.Text = product.Price.ToString();

                // Choose the selected category after binding
                categoryCombo.DataBound += new EventHandler(
                    (s, ev) => { categoryCombo.Items.FindByValue(product.CategoryId.ToString()).Selected = true; });

                // Bind the notifications details
                chkNotifyBelowThreshold.Checked = product.NotifyBelowThreshold;
                txtThreshold.Text = product.Threshold.ToString();
                chkNotifyDeadStock.Checked = product.NotifyUnordered;
                txtMaxDaysFromLastOrder.Text = product.MaxDaysFromLastOrder.ToString();
            }
        }

        //function checks if the input is a number
        public bool Check(string str)
        {
            double Num;
            bool isNum = (double.TryParse(str, out Num));
            return isNum;
        }

        //function changes string to double
        public double Change(String s)
        {
            String st = s.Substring(0);
            double x = double.Parse(st);
            return x;
        }

        //function activated when the administrater presses "ok"
        protected void okBtn_Click(object sender, EventArgs e)
        {
            Queries queries = new Queries();
            int productId = Int32.Parse(Request.QueryString["productId"]);

            //making sure all text boxes have been filled
            if (nameTxtbox.Text == "" || priceTxtbox.Text == "" && Check(priceTxtbox.Text))
            {
                //if something is missing- print apropriot message to screan.
                empty.Text = ".קלט לא תקין";
            }
            else
            {   //making sure the new product does not exist in our data base.
                if (queries.CheckProductNameColision(productId, nameTxtbox.Text))
                {
                    // Disable the buttons so the user can't interfere
                    backBtn.Enabled = false;
                    okBtn.Enabled = false;

                    // If the field items in stock or threshold wasn't changed or is not numeric, save it as 0
                    int threshold = 0;
                    Int32.TryParse(txtThreshold.Text, out threshold);

                    int maxDaysFromLastOrder = 365;
                    Int32.TryParse(txtMaxDaysFromLastOrder.Text, out maxDaysFromLastOrder);

                    //adding the new client into our database
                    queries.EditProduct(productId, nameTxtbox.Text, Change(priceTxtbox.Text),
                        Int32.Parse(categoryCombo.SelectedItem.Value),
                        threshold, chkNotifyBelowThreshold.Checked, maxDaysFromLastOrder,
                        chkNotifyDeadStock.Checked);

                    // Announce success and wait for 2 seconds before redirecting
                    empty.Text = "המוצר עודכן בהצלחה";
                    redirectionTimer.Enabled = true;
                }
                //if the client already exists- print apropriate message to screan
                else
                {
                    empty.Text = "שם המוצר כבר נמצא במערכת";
                }
            }
        }

        protected void backBtn_Click(object sender, EventArgs e)
        {
            Response.Redirect("~/Admin/ChooseProduct.aspx");
        }

        /// <summary>
        /// Redirect back to the admin menu after a few seconds
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void redirectionTimer_Tick(object sender, EventArgs e)
        {
            Response.Redirect("~/Admin/AdminMenu.aspx");
        }
    }
}